/* 
 * Copyright 2012 DevDan
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.devdan.headsetfix;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.ToggleButton;
import static com.devdan.headsetfix.HeadsetCommonConstants.*;

public class HeadsetfixActivity extends Activity {
    private static final int NUMBER_PICKER_RESULT = 1002;
	protected static final String TAG = null;	
    Intent serviceIntent;
    SharedPreferences settings;
    SharedPreferences.Editor settingsEditor;

    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        boolean functionalityActive = false;
        if (FULL_VERSION) {
        	functionalityActive = true;
        }
        else {
            TrialChecker trialChecker = new TrialChecker();
            functionalityActive = !trialChecker.isTrialPeriodExceeded(this);
        }
        if (!functionalityActive) {
        	stopHeadsetService();
        	doNotStartOnBoot();
        	// Show link to pro version
        	AlertDialog.Builder ad = new AlertDialog.Builder(this);
            ad.setTitle(R.string.s_app_expired_dialog_title);
            ad.setMessage(R.string.s_trial_over);
            ad.setPositiveButton(R.string.s_get_from_market, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int whichButton) {
                  Intent i = new Intent(Intent.ACTION_VIEW, 
                                                Uri.parse("http://market.android.com/search?q=pname:com.devdan.headsetfix"));
                  startActivity(i);
                  finish();
               }
             }).show();   
        }
        // Trial period not expired yet or full version
        else {
	
	        setContentView(R.layout.main);   
	
	        settings = getSharedPreferences(PREFSFILE, MODE_PRIVATE);       
	        settingsEditor = settings.edit();        
	      
	
	        if (settings.getBoolean(KEY_ENABLED , SERVICE_ACTIVE_AT_FIRST_START_OF_APP)) {
	        	startHeadsetService();
	        	startOnBoot();
	        }
	
	        // Set gui elements     
	        
	        final ToggleButton toggleOnOff = (ToggleButton) findViewById(R.id.toggleOnOff);
	        toggleOnOff.setChecked(settings.getBoolean(KEY_ENABLED , SERVICE_ACTIVE_AT_FIRST_START_OF_APP));
	        
	        toggleOnOff.setOnClickListener(new Button.OnClickListener() {
	   		 
	            public void onClick(View v) {
	            	if (toggleOnOff.isChecked()) {
	            		settingsEditor.putBoolean(KEY_ENABLED, true);   
	            		settingsEditor.commit();
	            		startHeadsetService();
	            		startOnBoot();
	            	}
	            	else {
	            		settingsEditor.putBoolean(KEY_ENABLED, false);
	            		settingsEditor.commit();            		
	            		stopHeadsetService();
	            		doNotStartOnBoot();	     		
	            	}
	            }
	
	        });        
	        
	        RadioButton radioVoicedialer = (RadioButton) findViewById(R.id.radioVoicedialer);
	        RadioButton radioRedial = (RadioButton) findViewById(R.id.radioRedial);
	        RadioButton radioDialNumber = (RadioButton) findViewById(R.id.radioDialNumber);
	
	    	// Disable button unless it is checked if voice dialer is installed
	    	radioVoicedialer.setEnabled(false);
	   	
	    	radioRedial.setOnClickListener(new Button.OnClickListener() {
	    		 
	            public void onClick(View v) {
		        		settingsEditor.putInt(BUTTON_BEHAVIOUR, OPTION_REDIAL);
		        		settingsEditor.commit();
		        		if (settings.getBoolean(KEY_ENABLED , SERVICE_ACTIVE_AT_FIRST_START_OF_APP)) {
		        			restartHeadsetService();
		        		}
	            	}
	        });
	    	
	    	radioDialNumber.setOnClickListener(new Button.OnClickListener() {
	   		 
	            public void onClick(View v) {
		        		settingsEditor.putInt(BUTTON_BEHAVIOUR, OPTION_DIAL_NUMBER);
		        		settingsEditor.commit();
		        		if (settings.getBoolean(KEY_ENABLED , SERVICE_ACTIVE_AT_FIRST_START_OF_APP)) {
		        			restartHeadsetService();            	
		        		}
	            	}
	        });
	    	
	        // Check if voice dialer is installed
	        if (isAppInstalled("com.android.voicedialer")) {
	        	radioVoicedialer.setEnabled(true);
	        	
	        	radioVoicedialer.setOnClickListener(new Button.OnClickListener() {
	                public void onClick(View v) {
	                		settingsEditor.putInt(BUTTON_BEHAVIOUR, OPTION_VOICE_DIALER);
	                		settingsEditor.commit();
	                		if (settings.getBoolean(KEY_ENABLED , SERVICE_ACTIVE_AT_FIRST_START_OF_APP)) {
	                			restartHeadsetService();
	                		}        		
	                	}
	
	            });        	
	        }
	        else {
	        	// If voice dialer is not available anymore (because of uninstall etc.)
	        	// but set as the button behaviour, it must be switched to default.
	        	if (settings.getInt(BUTTON_BEHAVIOUR, OPTION_REDIAL) == OPTION_VOICE_DIALER) {
	        		settingsEditor.putInt(BUTTON_BEHAVIOUR, OPTION_REDIAL);
	        		settingsEditor.commit();        		
	        	}
	        }
	    	switch (settings.getInt(BUTTON_BEHAVIOUR, OPTION_REDIAL)) {
				case OPTION_REDIAL:
					radioRedial.setChecked(true);
					break;
				case OPTION_VOICE_DIALER:
					radioVoicedialer.setChecked(true);
					break;
				case OPTION_DIAL_NUMBER:
					radioDialNumber.setChecked(true);
					break;
	    	}
	
	    	Button chooseNumberButton = (Button) findViewById(R.id.chooseNumberButton);    	
	
	    	chooseNumberButton.setOnClickListener(new Button.OnClickListener() {
	   		 
	            public void onClick(View v) {
	            	pickPhoneNumber();
	            }
	        });    	
	    	
	        final EditText numberEditText = (EditText) findViewById(R.id.phoneNumber);
	        numberEditText.setText((settings.getString(KEY_CUSTOM_PHONE_NUMBER , "")), TextView.BufferType.EDITABLE);
	        
	        numberEditText.addTextChangedListener(new TextWatcher() {
	            public void afterTextChanged(Editable s) {
	            	String number = numberEditText.getText().toString();
	        		settingsEditor.putString(KEY_CUSTOM_PHONE_NUMBER, number);
	        		settingsEditor.commit(); 
	        		if (settings.getBoolean(KEY_ENABLED , SERVICE_ACTIVE_AT_FIRST_START_OF_APP)) {
	        			restartHeadsetService();
	        		}         		
	                
	            }
	
				@Override
				public void beforeTextChanged(CharSequence arg0, int arg1,
						int arg2, int arg3) {
					
				}
	
				@Override
				public void onTextChanged(CharSequence s, int start, int before,
						int count) {
					
				}        
	        });
        }
    }

	public void onDestroy(Bundle savedInstanceState) {
    }
    
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
        case KeyEvent.KEYCODE_BACK:

            this.finish();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }    

    protected void pickPhoneNumber() {
        Intent intent = new Intent(this, ContactPickerActivity.class);
        startActivityForResult(intent,NUMBER_PICKER_RESULT);	  
	}
    
    public void showVoiceDialer() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setClassName("com.android.voicedialer", "com.android.voicedialer.VoiceDialerActivity");
        startActivity(intent);
    }
    private boolean isAppInstalled(String uri) {

        PackageManager pm = getPackageManager();
        boolean app_installed = false;
        try
        {
               pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
               app_installed = true;
        }
        catch (PackageManager.NameNotFoundException e)
        {
               app_installed = false;
        }
        return app_installed ;
    }

	private void startHeadsetService() {
        if (serviceIntent == null) {
    		serviceIntent = new Intent();
            serviceIntent.setClassName(getPackageName(), HeadsetButtonListenService.class.getName());	            		
        }
        // Services are unique, start if already started does not harm.
        startService(serviceIntent);		
	}

	private void stopHeadsetService() {
		if (serviceIntent == null) {
			serviceIntent = new Intent();
            serviceIntent.setClassName(getPackageName(), HeadsetButtonListenService.class.getName());                                    			
		}
			stopService(serviceIntent);
	}

	private void restartHeadsetService() {
		stopHeadsetService();
		startHeadsetService();
	}

	private void startOnBoot() {
		Context context = getApplicationContext();
		ComponentName component = new ComponentName(context, HeadsetButtonBootReceiver.class);
		int status = context.getPackageManager().getComponentEnabledSetting(component);
		if(! (status == PackageManager.COMPONENT_ENABLED_STATE_ENABLED || status == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT))
		{
			context.getPackageManager().setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_ENABLED , PackageManager.DONT_KILL_APP);
		}
	}
	
	private void doNotStartOnBoot() {
		Context context = getApplicationContext();
		ComponentName component = new ComponentName(context, HeadsetButtonBootReceiver.class);
		int status = context.getPackageManager().getComponentEnabledSetting(component);
		if(status == PackageManager.COMPONENT_ENABLED_STATE_ENABLED || status == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT)
		{
			context.getPackageManager().setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_DISABLED , PackageManager.DONT_KILL_APP);
		}		
	}
	
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
	    if (resultCode == RESULT_OK) {  
	    	Bundle extras = data.getExtras();	    	
	    	if (requestCode == NUMBER_PICKER_RESULT) {
	    		String number = extras.getString(KEY_SELECTED_PHONE_NUMBER);
	            EditText numberEditText = (EditText) findViewById(R.id.phoneNumber);
	            numberEditText.setText(number, TextView.BufferType.EDITABLE);
        		settingsEditor.putString(KEY_CUSTOM_PHONE_NUMBER, number);
        		settingsEditor.commit(); 
        		if (settings.getBoolean(KEY_ENABLED , SERVICE_ACTIVE_AT_FIRST_START_OF_APP)) {
        			restartHeadsetService();
        		}         		
	    	}
	    }
	}
}